﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.Linq;
using System.Text;

namespace BLL.Dal
{
    public class SysMenuDAL
    {
        public SysMenuDAL()
        { }
        #region  BasicMethod
        /// <summary>
        /// 是否存在该记录
        /// </summary>
        public bool Exists(string menuCode)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("select count(1) from tbSysMenu");
            strSql.Append(" where menuCode=@menuCode ");
            OleDbParameter[] parameters = {
					new OleDbParameter("@menuCode", OleDbType.VarChar,255)			};
            parameters[0].Value = menuCode;

            return DbHelperOleDb.Exists(strSql.ToString(), parameters);
        }


        /// <summary>
        /// 增加一条数据
        /// </summary>
        public bool Add(Model.SysMenu model)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("insert into tbSysMenu(");
            strSql.Append("menuCode,menuName,parentCode,indexNum,isLeaf,isActive,url,menuLevel,iconName)");
            strSql.Append(" values (");
            strSql.Append("@menuCode,@menuName,@parentCode,@indexNum,@isLeaf,@isActive,@url,@menuLevel,@iconName)");
            OleDbParameter[] parameters = {
					new OleDbParameter("@menuCode", OleDbType.VarChar,255),
					new OleDbParameter("@menuName", OleDbType.VarChar,255),
					new OleDbParameter("@parentCode", OleDbType.VarChar,255),
					new OleDbParameter("@indexNum", OleDbType.Integer,4),
					new OleDbParameter("@isLeaf", OleDbType.Boolean,1),
					new OleDbParameter("@isActive", OleDbType.Boolean,1),
					new OleDbParameter("@url", OleDbType.VarChar,255),
					new OleDbParameter("@menuLevel", OleDbType.Integer,4),
					new OleDbParameter("@iconName", OleDbType.VarChar,255)};
            parameters[0].Value = model.menuCode;
            parameters[1].Value = model.menuName;
            parameters[2].Value = model.parentCode;

            int indexNum = GetIndexNum(model.parentCode) + 1;
            //设定排序号
            parameters[3].Value = indexNum;
            parameters[4].Value = model.isLeaf;
            parameters[5].Value = model.isActive;
            parameters[6].Value = model.url;
            parameters[7].Value = model.menuLevel;
            parameters[8].Value = model.iconName;

            int rows = DbHelperOleDb.ExecuteSql(strSql.ToString(), parameters);
            if (rows > 0)
            {
                //更新上级节点的叶子节标识
                if (model.parentCode.Trim() != "Root")
                {
                    SetIsLeaf(model.parentCode, false);
                }
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 获取当前父节点的所有孩子数
        /// </summary>
        /// <param name="parentCode">父级节点标识</param>
        /// <returns></returns>
        public int GetIndexNum(string parentCode)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("select count(*) from tbSysMenu ");
            strSql.Append(" where parentCode=@parentCode ");
            OleDbParameter[] parameters = {
					new OleDbParameter("@parentCode", OleDbType.VarChar,255)};

            parameters[0].Value = parentCode;

            object obj = DbHelperOleDb.GetSingle(strSql.ToString(), parameters);

            if (obj != null)
            {
                return (int)obj;
            }
            return 0;
        }

        /// <summary>
        /// 设置节点的叶子标识
        /// </summary>
        /// <param name="menuCode">菜单标识</param>
        /// <param name="blLeaf">是否叶子标识</param>
        /// <returns>执行成功</returns>
        public bool SetIsLeaf(string menuCode, bool blLeaf)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("update tbSysMenu set ");
            strSql.Append("isLeaf=@isLeaf ");
            strSql.Append(" where menuCode=@menuCode ");
            OleDbParameter[] parameters = {
					new OleDbParameter("@isLeaf", OleDbType.Boolean,1),
					new OleDbParameter("@menuCode", OleDbType.VarChar,255)};

            parameters[0].Value = blLeaf;
            parameters[1].Value = menuCode;

            int rows = DbHelperOleDb.ExecuteSql(strSql.ToString(), parameters);
            if (rows > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 更新一条数据
        /// </summary>
        public bool Update(Model.SysMenu model)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("update tbSysMenu set ");
            strSql.Append("menuName=@menuName,");
            strSql.Append("parentCode=@parentCode,");
            strSql.Append("indexNum=@indexNum,");
            strSql.Append("isLeaf=@isLeaf,");
            strSql.Append("isActive=@isActive,");
            strSql.Append("url=@url,");
            strSql.Append("menuLevel=@menuLevel,");
            strSql.Append("iconName=@iconName");
            strSql.Append(" where menuCode=@menuCode ");
            OleDbParameter[] parameters = {
					new OleDbParameter("@menuName", OleDbType.VarChar,255),
					new OleDbParameter("@parentCode", OleDbType.VarChar,255),
					new OleDbParameter("@indexNum", OleDbType.Integer,4),
					new OleDbParameter("@isLeaf", OleDbType.Boolean,1),
					new OleDbParameter("@isActive", OleDbType.Boolean,1),
					new OleDbParameter("@url", OleDbType.VarChar,255),
					new OleDbParameter("@menuLevel", OleDbType.Integer,4),
					new OleDbParameter("@iconName", OleDbType.VarChar,255),
					new OleDbParameter("@menuCode", OleDbType.VarChar,255)};
            parameters[0].Value = model.menuName;
            parameters[1].Value = model.parentCode;
            parameters[2].Value = model.indexNum;
            parameters[3].Value = model.isLeaf;
            parameters[4].Value = model.isActive;
            parameters[5].Value = model.url;
            parameters[6].Value = model.menuLevel;
            parameters[7].Value = model.iconName;
            parameters[8].Value = model.menuCode;

            int rows = DbHelperOleDb.ExecuteSql(strSql.ToString(), parameters);
            if (rows > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 删除一条数据
        /// </summary>
        public bool Delete(string menuCode)
        {
            Model.SysMenu delModel = GetModel(menuCode);
            StringBuilder strSql = new StringBuilder();
            strSql.Append("delete from tbSysMenu ");
            strSql.Append(" where menuCode=@menuCode ");
            OleDbParameter[] parameters = {
					new OleDbParameter("@menuCode", OleDbType.VarChar,255)			};
            parameters[0].Value = menuCode;

            int rows = DbHelperOleDb.ExecuteSql(strSql.ToString(), parameters);
            if (rows > 0)
            {
                UpdateIndexNum(delModel.parentCode, delModel.indexNum);
                DelAllChild(menuCode);
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 更新菜单的行号
        /// </summary>
        public void UpdateIndexNum(string nodeParentCode, int? nodeIndexNum)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("update  tbSysMenu set indexNum=indexNum-1  ");
            strSql.Append(" where parentCode=@parentCode and indexNum>=@indexNum");
            OleDbParameter[] parameters = {
					new OleDbParameter("@menuCode", OleDbType.VarChar,255),	
                    new OleDbParameter("@indexNum", OleDbType.Integer)	};
            parameters[0].Value = nodeParentCode;
            parameters[1].Value = nodeIndexNum;

            int rows = DbHelperOleDb.ExecuteSql(strSql.ToString(), parameters);

        }

        /// <summary>
        /// 删除所有子级节点
        /// </summary>
        /// <param name="strParentCode">父节点标识</param>
        public void DelAllChild(string strParentCode)
        {
            string strSql = "select * from tbSysMenu where parentCode=@parentCode";
            OleDbParameter[] parameters = {
					new OleDbParameter("@parentCode", OleDbType.VarChar,255)			};
            parameters[0].Value = strParentCode;

            DataTable dtAllChild = DbHelperOleDb.Query(strSql, parameters).Tables[0];

            for (int i = 0; i < dtAllChild.Rows.Count; i++)
            {
                StringBuilder strSqlTemp = new StringBuilder();
                strSqlTemp.Append("delete from tbSysMenu ");
                strSqlTemp.Append(" where menuCode=@menuCode ");
                OleDbParameter[] parametersTemp = {
					new OleDbParameter("@menuCode", OleDbType.VarChar,255)			};
                parameters[0].Value = dtAllChild.Rows[i]["menuCode"].ToString();

                int rows = DbHelperOleDb.ExecuteSql(strSqlTemp.ToString(), parameters);

                DelAllChild(dtAllChild.Rows[i]["menuCode"].ToString());
            }
        }

        /// <summary>
        /// 批量删除数据
        /// </summary>
        public bool DeleteList(string menuCodelist)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("delete from tbSysMenu ");
            strSql.Append(" where menuCode in (" + menuCodelist + ")  ");
            int rows = DbHelperOleDb.ExecuteSql(strSql.ToString());
            if (rows > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }


        /// <summary>
        /// 得到一个对象实体
        /// </summary>
        public Model.SysMenu GetModel(string menuCode)
        {

            StringBuilder strSql = new StringBuilder();
            strSql.Append("select menuCode,menuName,parentCode,indexNum,isLeaf,isActive,url,menuLevel,iconName from tbSysMenu ");
            strSql.Append(" where menuCode=@menuCode ");
            OleDbParameter[] parameters = {
					new OleDbParameter("@menuCode", OleDbType.VarChar,255)			};
            parameters[0].Value = menuCode;

            Model.SysMenu model = new Model.SysMenu();
            DataSet ds = DbHelperOleDb.Query(strSql.ToString(), parameters);
            if (ds.Tables[0].Rows.Count > 0)
            {
                return DataRowToModel(ds.Tables[0].Rows[0]);
            }
            else
            {
                return null;
            }
        }


        /// <summary>
        /// 得到一个对象实体
        /// </summary>
        public Model.SysMenu DataRowToModel(DataRow row)
        {
            Model.SysMenu model = new Model.SysMenu();
            if (row != null)
            {
                if (row["menuCode"] != null)
                {
                    model.menuCode = row["menuCode"].ToString();
                }
                if (row["menuName"] != null)
                {
                    model.menuName = row["menuName"].ToString();
                }
                if (row["parentCode"] != null)
                {
                    model.parentCode = row["parentCode"].ToString();
                }
                if (row["indexNum"] != null && row["indexNum"].ToString() != "")
                {
                    model.indexNum = int.Parse(row["indexNum"].ToString());
                }
                if (row["isLeaf"] != null && row["isLeaf"].ToString() != "")
                {
                    if ((row["isLeaf"].ToString() == "1") || (row["isLeaf"].ToString().ToLower() == "true"))
                    {
                        model.isLeaf = true;
                    }
                    else
                    {
                        model.isLeaf = false;
                    }
                }
                if (row["isActive"] != null && row["isActive"].ToString() != "")
                {
                    if ((row["isActive"].ToString() == "1") || (row["isActive"].ToString().ToLower() == "true"))
                    {
                        model.isActive = true;
                    }
                    else
                    {
                        model.isActive = false;
                    }
                }
                if (row["url"] != null)
                {
                    model.url = row["url"].ToString();
                }
                if (row["menuLevel"] != null && row["menuLevel"].ToString() != "")
                {
                    model.menuLevel = int.Parse(row["menuLevel"].ToString());
                }
                if (row["iconName"] != null)
                {
                    model.iconName = row["iconName"].ToString();
                }
            }
            return model;
        }

        /// <summary>
        /// 获得数据列表
        /// </summary>
        public DataSet GetList(string strWhere)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("select menuCode,menuName,parentCode,indexNum,isLeaf,isActive,url,menuLevel,iconName ");
            strSql.Append(" FROM tbSysMenu ");
            if (strWhere.Trim() != "")
            {
                strSql.Append(" where " + strWhere);
            }
            return DbHelperOleDb.Query(strSql.ToString());
        }

        /// <summary>
        /// 获取记录总数
        /// </summary>
        public int GetRecordCount(string strWhere)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("select count(1) FROM tbSysMenu ");
            if (strWhere.Trim() != "")
            {
                strSql.Append(" where " + strWhere);
            }
            object obj = DbHelperSQL.GetSingle(strSql.ToString());
            if (obj == null)
            {
                return 0;
            }
            else
            {
                return Convert.ToInt32(obj);
            }
        }
        /// <summary>
        /// 分页获取数据列表
        /// </summary>
        public DataSet GetListByPage(string strWhere, string orderby, int startIndex, int endIndex)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("SELECT * FROM ( ");
            strSql.Append(" SELECT ROW_NUMBER() OVER (");
            if (!string.IsNullOrEmpty(orderby.Trim()))
            {
                strSql.Append("order by T." + orderby);
            }
            else
            {
                strSql.Append("order by T.menuCode desc");
            }
            strSql.Append(")AS Row, T.*  from tbSysMenu T ");
            if (!string.IsNullOrEmpty(strWhere.Trim()))
            {
                strSql.Append(" WHERE " + strWhere);
            }
            strSql.Append(" ) TT");
            strSql.AppendFormat(" WHERE TT.Row between {0} and {1}", startIndex, endIndex);
            return DbHelperOleDb.Query(strSql.ToString());
        }


        #endregion  BasicMethod
        #region  ExtensionMethod

        /// <summary>
        /// 获取用户菜单
        /// </summary>
        /// <returns></returns>
        public DataTable GetUserMenu()
        {
            DataTable dtReturn = GetList("").Tables[0];
            return dtReturn;
        }

        #endregion  ExtensionMethod
    }
}
